<script setup>
import { inject, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import Card from '@/views/new-screen/components/card.vue'
import DrawEcharts from '@/components/draw-echarts.vue'
import yycg from '../../../../assets/imgs/bt_yycg_nor.png'
import sjfws from '../../../../assets/imgs/bt_sjfws_nor.png'
import fkzrs from '../../../../assets/imgs/bt_fkzrs_nor.png'
import jzmj from '../../../../assets/imgs/ic_jzmj.png'
import rzqys from '../../../../assets/imgs/ic_rzqys.png'
import fwzs from '../../../../assets/imgs/ic_fwzs.png'
import test1 from '../../../../assets/imgs/img1@2x.png'
import test2 from '../../../../assets/imgs/img2@2x.png'
import {
  getHouseType,
  getHouseYearRanking
} from '../api.js'
import icon_house from '@/assets/imgs/bt_sy.png'
import icon_person from '@/assets/imgs/ic_rygj.png'

const props = defineProps({
  isExpanded: Boolean,
  activeName: String,
})

const getChartPieOption = ({ list, image }) => {
  const total = list.reduce((a, b) => a + b.value, 0)
  return {
    tooltip: {
      trigger: 'item',
      formatter: '{b} <br/> {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      top: 'middle',
      left: '65%',
      data: list.map(item => item.name),
      itemWidth: 10,
      itemHeight: 10,
      icon: 'circle',
      itemGap: 10,
      textStyle: {
        color: '#fff',
        fontSize: 12
      },
      formatter: (name) => {
        const value = list.find(item => item.name === name).value
        const per = parseFloat((value / total * 100).toFixed(2))
        return name + '  ' + value + '  ' + per + '%'
      }
    },
    series: [
      {
        name: '按年龄',
        type: 'pie',
        radius: ['32%', '46%'],
        center: ['36%', '50%'],
        padAngle: 3, // 轻微的角度间隙
        labelLine: {
          length: 5
        },
        inverse: true,
        label: {
          formatter: '{b|{b}}\n{hr|}\n{per|{d}%}  ',
          rich: {
            b: {
              color: '#ffffff',
              fontSize: 14,
            },
            hr: {
              borderColor: '#8C8D8E',
              width: '100%',
              borderWidth: 1,
              height: 0
            },
            c: {
              color: '#ffffff',
              fontSize: 14,
              lineHeight: 28
            },
            unit: {
              color: '#ccc',
              fontWeight: 'normal',
            },
            per: {
              color: '#ffffff',
              lineHeight: 28
              // backgroundColor: '#4C5058',
              // padding: [3, 4],
              // borderRadius: 4
            }
          }
        },
        data: list,
      }
    ],
    // 添加 graphic 组件显示图片
    graphic: {
      elements: [{
        type: 'image',
        key: 'centerImage',
        z: 100,
        style: {
          image: image, // 你的图片路径
          width: 50,
          height: 50
        },
        left: '30%',
        top: 'center'
      }]
    },
    backgroundColor: {
      type: 'linear',
      x: 0,
      y: 0,
      x2: 1,
      y2: 0,
      colorStops: [{
          offset: 0, color: '#01153c21' // 0% 处的颜色
      }, {
          offset: 1, color: '#01153c89' // 100% 处的颜色
      }],
      global: false // 缺省为 false
    },
  }
}

const getChartBarOption = (data) => {
  return {
    backgroundColor: {
      type: 'linear',
      x: 0,
      y: 0,
      x2: 1,
      y2: 0,
      colorStops: [{
          offset: 0, color: '#01153c21' // 0% 处的颜色
      }, {
          offset: 1, color: '#01153c89' // 100% 处的颜色
      }],
      global: false // 缺省为 false
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        // Use axis to trigger tooltip
        type: 'shadow' // 'shadow' as default; can also be 'line' or 'shadow'
      }
    },
    legend: {
      top: 'top',
      left: 'center',
      itemWidth: 10,
      itemHeight: 10,
      itemGap: 30,
    },
    grid: {
      left: '3%',
      right: '4%',
      top: '23%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.xAxis,
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '总幢数',
        type: 'bar',
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
                offset: 0, color: '#FFE676' // 0% 处的颜色
            }, {
                offset: 1, color: '#FF933A' // 100% 处的颜色
            }],
            global: false // 缺省为 false
          }
        },
        emphasis: {
          focus: 'series'
        },
        data: data['总幢数'], // [320, 302, 301, 334, 390, 330, 320]
      },
      {
        name: '住宅',
        type: 'bar',
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
                offset: 0, color: '#CBFBFF' // 0% 处的颜色
            }, {
                offset: 1, color: '#02AAFA' // 100% 处的颜色
            }],
            global: false // 缺省为 false
          }
        },
        emphasis: {
          focus: 'series'
        },
        data: data['住宅'], // [120, 132, 101, 134, 90, 230, 210]
      },
      {
        name: '非住宅',
        type: 'bar',
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
                offset: 0, color: '#BAFFF2' // 0% 处的颜色
            }, {
                offset: 1, color: '#10FFC1' // 100% 处的颜色
            }],
            global: false // 缺省为 false
          }
        },
        emphasis: {
          focus: 'series'
        },
        data: data['非住宅'], // [120, 132, 101, 134, 90, 230, 210]
      }
    ]
  }
}


const dangerousHouseChartPieRef = ref(null)
const dangerousNonHouseChartPieRef = ref(null)
const updateChartDangerousHouse = (data) => {
  const data_1 = data['住宅'].map((item) => ({ value: item.count, name: item.type }))
  dangerousHouseChartPieRef.value?.updateOption(getChartPieOption({ list: data_1, image: icon_house }))
  
  const data_2 = data['非住宅'].map((item) => ({ value: item.count, name: item.type }))
  dangerousNonHouseChartPieRef.value?.updateOption(getChartPieOption({ list: data_2, image: icon_house }))
}

let dangerousHouseTotal = ref([
  {
    label: '50年以上住宅',
    count: 1241,
    countUnit: '幢',
    area: 52041,
    areaUnit: '万平',
    img: fwzs,
  },
  {
    label: '50年以上非住宅',
    count: 1241,
    countUnit: '幢',
    area: 52041,
    areaUnit: '万平',
    img: fwzs,
  },
])

const updateDataHouseYearOverview = (data) => {
  data.type?.forEach((item) => {
    const one = dangerousHouseTotal.value.find((e) => e.label === item.type)
    if (one) { 
      one.count = item.count
      one.area = item.area
    }
  })
}

const houseYearAnalysisChartBarRef = ref(null)
const updateChartHouseYearAnalysis = (data) => {
  const opt = {
    xAxis: data.legend, // ['20年内', '20-30年', '30-40年', '40-50年', '50年以上'],
    '总幢数': data['total'], 
    '住宅': data['住宅'],
    '非住宅': data['非住宅'],
  }
  const updateOption = getChartBarOption(opt)
  houseYearAnalysisChartBarRef.value?.updateOption(updateOption)
}

const reqData = () => {
  Promise.all([
    getHouseType(),
    getHouseYearRanking(),
  ])
  .then(([type, ranking]) => {
    if (type.success) {
      updateChartDangerousHouse(type.data)
    }
    if (ranking.success) {
      updateDataHouseYearOverview(ranking.data)
      updateChartHouseYearAnalysis(ranking.data)
    }
  })
}


onMounted(async () => {
  reqData()
})
</script>

<template>
  <div :class="['right', isExpanded ? 'active' : '']">
    <card name="危房房屋类型" class="dangerous-house-type">
      <!-- <div class="title">各城区危房数量</div> -->
      <div class="chart">
        <draw-echarts
          ref="dangerousHouseChartPieRef"
          width="420"
          height="180"
          :options="{}"
        ></draw-echarts>
      </div>
      <div class="chart">
        <draw-echarts
          ref="dangerousNonHouseChartPieRef"
          width="420"
          height="180"
          :options="{}"
        ></draw-echarts>
      </div>
    </card>
    <card name="房屋年限分析" class="house-year-analysis">
      <div class="box-list">
        <div class="box-item" v-for="(item, i) in dangerousHouseTotal" :key="i">
          <div class="bg"></div>
          <div class="box-head">
            <img class="icon" :src="item.img" alt />
            <span class="title">{{ item.label }}</span>
          </div>
          <div class="box-content">
            <div class="box-item-line">
              {{ item.count }}
              <span class="unit">{{ item.countUnit }}</span>
            </div>
            <div class="box-item-line">
              {{ item.area }}
              <span class="unit">{{ item.areaUnit }}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="chart">
        <draw-echarts
          ref="houseYearAnalysisChartBarRef"
          width="420"
          height="280"
          :options="{}"
        ></draw-echarts>
      </div>
    </card>
  </div>
</template>

<style scoped lang="scss">
.right {
  .dangerous-house-type {
    height: 400px;
    margin-bottom: var(--card-margin-bottom);
    color: #eee;
  }

  .house-year-analysis {
    height: 400px;
    color: #fff;
    .box-list {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      .box-item {
        position: relative;
        width: 45%;
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-bottom: 40px;
        margin-left: 10px;
        border: 2px solid; // 设置边框宽度
        border-image: linear-gradient(90deg, #00EDF4, #081731) 1; // 渐变边框

        .bg {
          position: absolute;
          width: 100%;
          height: 100%;
        }

        .box-head {
          width: 100%;
          height: 40px;
          display: flex;
          align-items: center;
          background: linear-gradient(to right, #026B9F, #081731);
          .icon {
            object-fit: contain;
            width: 30px;
            height: 30px;
            margin-left: 6px;
            margin-right: 6px;
          }
          .title {
            font-size: 16px;
          }
        }
        .box-content {
          width: 100%;
          height: 80px;
          background: linear-gradient(to right, #05456C, #08162F);
          .box-item-line {
            display: flex;
            align-items: flex-end;
            justify-content: flex-start;
            margin-top: 10px;
            padding-left: 42px;
            
            font-weight: bold;
            font-size: 20px;
            color: #fff;
            .unit {
              color: #979797;
              font-size: 14px;
              margin-left: 2px;
            }
          }
        }
      }
    }
  }

}
</style>
